package com.zengdada.authority.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zengdada.authority.config.security.intercept.AuthorityUtil;
import com.zengdada.authority.mapper.DynamicTableToolbarMapper;
import com.zengdada.authority.model.AppUser;
import com.zengdada.authority.model.DynamicTable;
import com.zengdada.authority.model.DynamicTableToolbar;
import com.zengdada.authority.service.DynamicTableAuthorityService;
import com.zengdada.authority.service.DynamicTableColumnAuthorityService;
import com.zengdada.authority.service.EnhanceBaseService;
import com.zengdada.authority.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.Fn;
import tk.mybatis.mapper.weekend.WeekendSqls;
import tk.mybatis.mapper.weekend.reflection.Reflections;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2019/3/7 11:05
 * @Description:
 */
@Service
public class DynamicTableAuthorityServiceImpl extends EnhanceBaseService<DynamicTable> implements DynamicTableAuthorityService {

    @Autowired
    AuthorityUtil authorityUtil;
    @Autowired
    @Qualifier("dynamicTableColumnAuthorityServiceImpl")
    DynamicTableColumnAuthorityService dynamicTableColumnAuthorityService;
    @Autowired
    DynamicTableToolbarMapper dynamicTableToolbarMapper;

    @Override
    public void save(DynamicTable dynamicTable, String toolbarJsons) {
        AppUser user = authorityUtil.getLoginUser();
        dynamicTable.setModifyUser(user.getId());
        dynamicTable.setModifyTime(new Date());
        List<DynamicTableToolbar> dynamicTableToolbars = JSONObject.parseArray(toolbarJsons, DynamicTableToolbar.class);
        if (StringUtils.isBlank(dynamicTable.getId())) {
            try {
                CommonUtils.reflectObjectTransString(dynamicTable, false);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
            this.add(dynamicTable);
        } else {
            DynamicTable oldTable = this.selectById(dynamicTable.getId());
            this.updateById(dynamicTable);
            if (!oldTable.getDmlId().equals(dynamicTable.getDmlId())) //如果 dml语句更换了 强制更新数据列
                dynamicTableColumnAuthorityService.autoGenerationColumn(dynamicTable.getId(), true);
        }
        Example example = new Example(DynamicTableToolbar.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Reflections.fnToFieldName((Fn<DynamicTableToolbar, Object>) DynamicTableToolbar::getTableId), dynamicTable.getId());
        if (dynamicTableToolbars != null && dynamicTableToolbars.size() != 0) {
            List<String> ids = dynamicTableToolbars.stream().filter(e -> StringUtils.isNoneBlank(e.getId())).map(e -> e.getId()).collect(Collectors.toList());
            if (ids.size() > 0)
                criteria.andNotIn(Reflections.fnToFieldName((Fn<DynamicTableToolbar, Object>) DynamicTableToolbar::getId), ids);
            dynamicTableToolbarMapper.deleteByExample(example);
            for (DynamicTableToolbar tableToolbar : dynamicTableToolbars) {
                if (StringUtils.isBlank(tableToolbar.getId())) {
                    try {
                        CommonUtils.reflectObjectTransString(tableToolbar, false);
                    } catch (Exception e) {
                        throw new RuntimeException(e.getMessage());
                    }
                    tableToolbar.setTableId(dynamicTable.getId());
                    dynamicTableToolbarMapper.insertSelective(tableToolbar);
                } else {
                    dynamicTableToolbarMapper.updateByPrimaryKeySelective(tableToolbar);
                }
            }
        } else {
            dynamicTableToolbarMapper.deleteByExample(example);
        }
    }

    @Override
    public Map<String, Object> selectDetailedById(Object id) {
        Map<String, Object> map = super.selectDetailedById(id);
        if (map != null)
            map.put("toolbarData", dynamicTableToolbarMapper.selectByExample(new Example.Builder(DynamicTableToolbar.class).where(WeekendSqls.<DynamicTableToolbar>custom().andEqualTo(DynamicTableToolbar::getTableId, map.get("id"))).build()));
        return map;
    }
}
